<template>
  <div v-if="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <div style="display: flex; align-items: center; margin: 16px 0 24px">
        <px-button type="primary" icon="ArrowLeft" style="margin-right: 16px" @click="backMainPage">返回</px-button>
      </div>
      <px-form ref="formRef" :rules="rules" :inline="true" :model="formValue" label-position="right" label-width="120px">
        <EditDropDown dropdownTitle="入库信息">
          <template v-slot:content>
            <px-row>
              <div class="img">
                <div class="imgBox" />
                <div class="imgSize">基础信息</div>
              </div>
              <px-col :span="8">
                <px-form-item label="入库类型" prop="inType">
                  <px-input v-model="formValue.inType" placeholder="自动带出入库类型" maxlength="80" clearable disabled />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="入库单号" prop="inNum">
                  <px-input v-model="formValue.inNum" placeholder="自动生成入库单号" maxlength="80" clearable disabled />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="操作人员" prop="inUserName">
                  <px-input v-model="formValue.inUserName" placeholder="自动带出入库操作人员" maxlength="50" disabled />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="申请时间">
                  <px-date-picker
                    v-model="formValue.actTime"
                    disabled
                    style="width: 100%"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetime"
                    placeholder="请选择时间"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="入库时间">
                  <px-date-picker
                    v-model="formValue.inDate"
                    style="width: 100%"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetime"
                    placeholder="请选择时间"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="24">
                <px-form-item label="备注" prop="remark">
                  <px-input
                    v-model="formValue.remark"
                    type="textarea"
                    placeholder="请输入备注"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    maxlength="1000"
                    clearable
                    show-word-limit
                  />
                </px-form-item>
              </px-col>
              <div v-if="formValue.inType !== 'Other'" class="img">
                <div class="imgBox" />
                <div class="imgSize">采购信息</div>
              </div>
              <px-col :span="8">
                <px-form-item v-if="formValue.inType == 'PR/PO'" label="关联PR/PO单号" prop="purchaseNum">
                  <px-input v-model="formValue.purchaseNum" placeholder="请输入" maxlength="80" clearable />
                </px-form-item>
                <px-form-item v-if="formValue.inType == 'MM领用'" label="关联MM领用单号" prop="purchaseNum">
                  <px-input v-model="formValue.purchaseNum" placeholder="请输入" maxlength="80" clearable />
                </px-form-item>
                <px-form-item v-if="formValue.inType == 'NPPA'" label="关联NPPA系统单号">
                  <px-input v-model="formValue.purchaseNum" placeholder="请输入" maxlength="80" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item v-if="formValue.inType == 'PR/PO' || formValue.inType == 'MM领用'" label="申请人员" prop="purchaseUser">
                  <px-select-v2
                    v-model="formValue.purchaseUser"
                    style="width: 100%"
                    filterable
                    clearable
                    :options="purchaseUserList"
                    placeholder="请选择创建人"
                  />
                  <!--  @change="changePeopleList" -->
                </px-form-item>
                <px-form-item v-else-if="formValue.inType == 'NPPA'" label="申请人员">
                  <px-input v-model="formValue.purchaseUser" placeholder="请输入" maxlength="80" clearable />
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
        <EditDropDown dropdownTitle="物资清单">
          <template v-slot:content>
            <div style="display: flex; margin-bottom: 8px" class="equip-table-btn">
              <px-button v-has="'ERC_MATERIAL_IN_QUERYMATERIAL'" type="primary" plain @click="dialogVisible = true">关联物资</px-button>
              <!-- <px-button v-has="'ERC_MATERIAL_IN_SCANADD'" type="primary" plain @click="dialogVisible = true">扫码添加</px-button> -->
              <!-- 等后端开发完一起上 -->
              <px-button
                v-has="'ERC_MATERIAL_IN_DOWNTEMPLATE'"
                style="margin-right: 8px; margin-left: 8px"
                type="primary"
                plain
                @click="templateDownload"
                >模板下载</px-button
              >
              <BatchUpload
                url="/ifp/erc/api/v1/material/inInventory/importData"
                title="导入"
                permission="ERC_MATERIAL_IN_UPLOAD"
                @updateUploadPage="addTableRowList"
              />
              <px-button v-has="'ERC_MATERIAL_IN_BATCHDELETE'" type="primary" plain @click="batchDelete">批量删除</px-button>
              <px-button v-has="'ERC_MATERIAL_IN_BATCHDELETE'" type="primary" plain style="margin-left: 8px" @click="addDialogVisible = true"
                >添加</px-button
              >
            </div>
            <px-table
              ref="multipleTableRef"
              :data="formValue.tableData"
              class="equip-table"
              size="small"
              max-height="400"
              border
              @selection-change="selectionChange"
            >
              <px-table-column type="selection" width="40" align="center" fixed="left" />
              <px-table-column type="index" label="序号" width="60" align="center" fixed="left" />
              <px-table-column
                v-for="(item, index) in tableColumns"
                :key="index"
                :label="item.label"
                :min-width="item.minWidth"
                :align="item.align"
                :show-overflow-tooltip="item.showOverflowTooltip"
                :fixed="item.fixed"
              >
                <template #default="scope">
                  <!-- 模糊搜索使用 -->
                  <div v-if="item.name">
                    <px-select-v2
                      v-model="scope.row.name"
                      style="width: 100%"
                      filterable
                      :options="nameList"
                      placeholder="Please select"
                      @change="filterName(scope.row.name, scope.$index)"
                    />
                  </div>

                  <div v-else-if="item.storeLocation">
                    <px-select v-model="scope.row.storeLocation" placeholder="请选择地块" clearable>
                      <px-option v-for="item in storeLocationList" :key="item.id" :label="item.name" :value="item.value" />
                    </px-select>
                  </div>
                  <!-- 入库数量 -->
                  <div v-else-if="item.quantity">
                    <px-input-number
                      v-model.number="scope.row.quantity"
                      :max="10000"
                      :min="0"
                      controls-position="right"
                      placeholder="请输入"
                      clearable
                    />
                  </div>
                  <!-- 供应商 -->
                  <div v-else-if="item.supplier">
                    <px-select v-model="scope.row.supplier" filterable placeholder="请选择AVL厂商">
                      <px-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.code" />
                    </px-select>
                  </div>
                  <!-- 生产日期   @change="changeStartTime"-->
                  <div v-else-if="item.productionDate">
                    <px-date-picker
                      v-model="scope.row.productionDate"
                      style="width: 100%"
                      placeholder="请选择生产日期"
                      type="date"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :clearable="false"
                      :disabled-date="disabledDate"
                      :disabled-hours="disabledHours"
                      :disabled-minutes="disabledMinutes"
                      :disabled-seconds="disabledSeconds"
                    />
                  </div>
                  <!-- 过期日期 -->
                  <div v-else-if="item.expirationDate">
                    <px-date-picker
                      v-model="scope.row.expirationDate"
                      style="width: 100%"
                      placeholder="请选择过期日期"
                      type="date"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :clearable="false"
                    />
                  </div>
                  <span v-else>{{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}</span>
                </template>
              </px-table-column>
              <px-table-column fixed="right" label="操作" width="50" align="center">
                <template #default="scope">
                  <px-button link type="danger" icon="Delete" @click="handleDelete(scope.$index)" />
                </template>
              </px-table-column>
            </px-table>
            <div />
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: space-between;
                width: 100vw;
                height: 40px;
                padding: 0 16px;
                margin: -6px 0 16px;
                background: #ecf5ff;
                border-radius: 4px;
              "
            >
              <div style="font-size: 14px; color: rgb(0 0 0 / 80%)">
                已选<span style="color: #3b82f6">{{ selectIds.length }}</span>
                <px-button link type="primary" style="margin-left: 5px" @click="clearSelection">清除已选</px-button>
              </div>
              <div>
                <span>批量设置入库量</span>
                <px-input-number
                  v-model.number="quantityNumber"
                  :disabled="selectIds.length === 0"
                  style="width: 150px; margin: 0 12px"
                  :min="0"
                  controls-position="right"
                  @change="batchSetQuantityNumber"
                />
                <px-select
                  v-model="supplierNumber"
                  :disabled="selectIds.length === 0"
                  style="width: 150px; margin-right: 12px"
                  filterable
                  placeholder="请选择AVL厂商"
                  @change="batchSetsupplierNumber"
                >
                  <px-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.name" />
                </px-select>
                <px-date-picker
                  v-model="productionDateNumber"
                  :disabled="selectIds.length === 0"
                  style="width: 150px; margin-right: 12px"
                  placeholder="请选择生产日期"
                  type="date"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :clearable="false"
                  :disabled-date="disabledDate"
                  :disabled-hours="disabledHours"
                  :disabled-minutes="disabledMinutes"
                  :disabled-seconds="disabledSeconds"
                  @change="batchSetproductionDateNumber"
                />
                <px-date-picker
                  v-model="expirationDateNumber"
                  :disabled="selectIds.length === 0"
                  style="width: 150px; margin-right: 8px"
                  placeholder="请选择过期日期"
                  type="date"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :clearable="false"
                  @change="batchSetexpirationDateNumber"
                />
              </div>
            </div>
          </template>
        </EditDropDown>
      </px-form>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button v-if="formValue.approveStatus === 'init' || props.drawerType === 'add'" type="primary" ghost @click="handleInit()"
        >保存草稿</px-button
      >
      <px-button type="primary" @click="handleSubmit(formRef)">提交</px-button>
    </div>
  </div>
  <!-- 选择关联物资弹窗 -->
  <AddMaterialDialog :visible="dialogVisible" :facCodeData="formValue.facCode" @closeDialog="closeDialog" @addTableRow="addTableRow" />
  <!-- 添加弹窗 -->
  <!-- :dialogType="dialogType" -->
  <AddMaterialType :addDialogVisible="addDialogVisible" :rowData="rowData" @AddTableRow="AddTableRow" @closeDialog="addDialogVisible = false" />
</template>
<script setup lang="ts">
import { queryDictData } from "@/api/erc/common";
import { ref, reactive, toRefs, watch, computed, getCurrentInstance, onMounted } from "vue";
import { PxMessage, PxMessageBox, PxTable, dayjs } from "px-ui";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import {
  getInNum,
  querynInventoryList,
  querySupplierList,
  materialInCreate,
  materialInEdit,
  likeByName,
  queryToolMaterial
} from "@/api/erc/material";
import AddMaterialDialog from "./AddMaterialDialog.vue";
import AddMaterialType from "./AddMaterialType.vue";
import BatchUpload from "../components/BatchUpload.vue";
import { getEmployeeIdAndName } from "@/utils/pengxi";

const { proxy }: any = getCurrentInstance();

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "addType", "drawerType", "sparePartsId", "userId", "username", "rowData"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);
const multipleTableRef = ref<InstanceType<typeof PxTable>>();
// 页面本身的值
const formRef = ref();
// 表单校验规则
const rules = computed(() => ({
  purchaseNum: [
    { required: true, message: formValue.value.inType == "PR/PO" ? "关联PR/PO单号不能为空" : "关联MM领用单号不能为空", trigger: ["blur", "change"] }
  ],
  purchaseUser: [{ required: true, message: "申请人员不能为空", trigger: ["blur", "change"] }]
}));
const state = reactive<any>({
  formValue: {
    inDate: "",
    actTime: "",
    name: "",
    supplier: "",
    purchaseNum: "",
    tableData: []
  },
  approverIdList: [],
  storeLocationList: [],
  tableColumns: [
    { prop: "name", label: "物资名称", minWidth: "153", showOverflowTooltip: true, fixed: "left", name: true },
    { prop: "typeName", label: "物资类型", minWidth: "154", showOverflowTooltip: true },
    { prop: "materialCode", label: "物资编码", minWidth: "150", showOverflowTooltip: true },
    { prop: "brand", label: "品牌", minWidth: "100", showOverflowTooltip: true },
    { prop: "specification", label: "规格型号", minWidth: "100", showOverflowTooltip: true },
    { prop: "unit", label: "单位", minWidth: "80", showOverflowTooltip: true },
    { prop: "storeLocation", label: "存放地块", minWidth: "150", showOverflowTooltip: true, storeLocation: true },
    { prop: "quantity", label: "入库数量", minWidth: "150", showOverflowTooltip: true, quantity: true },
    { prop: "supplier", label: "AVL厂商", minWidth: "150", showOverflowTooltip: true, supplier: true },
    { prop: "productionDate", label: "生产日期", minWidth: "150", showOverflowTooltip: true, productionDate: true },
    {
      prop: "expirationDate",
      label: "过期日期",
      minWidth: "150",
      showOverflowTooltip: true,
      returnQuantity: true,
      expirationDate: true
    }
  ],
  selectIds: [],
  quantityNumber: 0,
  supplierNumber: [],
  productionDateNumber: [],
  expirationDateNumber: [],
  dialogVisible: false,
  addDialogVisible: false,
  supplierList: [], //供货商下拉,
  nameList: [],
  purchaseUserList: []
});
const {
  formValue,
  tableColumns,
  selectIds,
  quantityNumber,
  supplierNumber,
  productionDateNumber,
  expirationDateNumber,
  dialogVisible,
  supplierList,
  nameList,
  storeLocationList,
  addDialogVisible,
  purchaseUserList
} = toRefs(state);
//生成入库单号
const getInNumNumber = async () => {
  const data = await getInNum();
  formValue.value.inNum = data;
};
// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && !props.isView) {
    formRef.value?.resetFields();
    querySupplier();
    queryName();
    querySelectList();
    formValue.value.inDate = dayjs().format("YYYY-MM-DD HH:mm:ss");
    formValue.value.actTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
    selectIds.value = [];
    quantityNumber.value = 0;
    supplierNumber.value = [];
    productionDateNumber.value = [];
    expirationDateNumber.value = [];
    const { userId, realName } = JSON.parse(localStorage.getItem("userInfo"));
    if (props.drawerType === "add") {
      getInNumNumber(); //生成入库单号
      formValue.value.inUserName = props.username + "-" + realName;
      formValue.value.inUserId = userId;
      formValue.value.inType = props.addType;
      formValue.value.tableData = [];
    } else if (props.drawerType === "edit") {
      formValue.value.actTime = props.rowData.actTime;
      formValue.value.inDate = props.rowData.inDate;
      formValue.value.approveStatus = props.rowData.approveStatus;
      formValue.value.inType = props.rowData.inType;
      formValue.value.inNum = props.rowData.inNum;
      formValue.value.inUserId = userId;
      formValue.value.inUserName = props.username + "-" + realName;
      formValue.value.purchaseNum = props.rowData.purchaseNum;
      formValue.value.purchaseUser = props.rowData.purchaseUser;
      formValue.value.remark = props.rowData.remark;
      const data = await querynInventoryList({ num: props.rowData.inNum });
      formValue.value.tableData = data || [];
    }
  } else {
    formValue.value = {};
  }
});
watch(selectIds, newselectIds => {
  if (newselectIds.length === 0) {
    quantityNumber.value = 0;
    supplierNumber.value = [];
    productionDateNumber.value = [];
    expirationDateNumber.value = [];
  }
});
onMounted(() => {
  querypurchaseUserList();
});
// 申请人员下拉框
const querypurchaseUserList = async () => {
  const tempPeopleListList = await getEmployeeIdAndName(["HSE", "ISEP", "ERC&FP"]);
  purchaseUserList.value = tempPeopleListList.map(item => {
    return {
      label: item.label,
      value: item.label
    };
  });
};
// 模版下载按钮
const templateDownload = async () => {
  proxy.download("post", "/erc/api/v1/material/inInventory/templateDownLoad", {}, "物资清单信息模板.xlsx");
};
// 模糊搜索功能
const queryName = async () => {
  const data: any = await likeByName({ name: "" });
  nameList.value = data.map(item => ({ label: item.name, value: item.name }));
};
// 选中模糊搜索的值
const filterName = async (name, index) => {
  const data: any = await likeByName({ name: name });
  const { tableData } = formValue.value;
  tableData[index] = data[0];
  tableData[index].materialCode = data[0].code;
  tableData[index].quantity = 0;
  formValue.value.tableData = [...tableData];
};
// 选择添加按钮后添加表格数据
const AddTableRow = async val => {
  // val子组件添加的弹跳数据
  const arrList = [val];
  const queryMaterialCodeList = await queryToolMaterial({ pageNum: 1, pageSize: 9999 });
  const aValue = () => {
    const target = queryMaterialCodeList.data.find(item => item.typeCode === arrList[0].typeCode && item.name === arrList[0].name);
    return target?.code;
  };
  // filtermaterialCode找到相同的数据并将materialCode回显
  const filtermaterialCode = await aValue();
  const arr = [{ ...val, id: formValue.value.tableData?.length + 1, materialCode: filtermaterialCode }];
  formValue.value.tableData = [...arr, ...formValue.value.tableData];
};
// 表格多选框选中-批量删除使用
const selectionChange = (val: any) => {
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.id) {
      selectIds.value.push(item.id);
    }
  });
  quantityNumber.value = 0;
};
// 批量删除按钮
const batchDelete = () => {
  if (selectIds.value.length == 0) {
    PxMessage.warning("请选择备件后操作");
    return;
  }
  selectIds.value.forEach(val => {
    formValue.value.tableData.forEach((v, i) => {
      if (val === v.id) {
        formValue.value.tableData.splice(i, 1);
      }
    });
  });
};
//清除已选
const clearSelection = () => {
  multipleTableRef.value!.clearSelection();
};
//获取供货商下拉
const querySupplier = async () => {
  const data = await querySupplierList({ name: formValue.value.supplier });
  supplierList.value = data;
};
// 禁用日期
const disabledDate = (time: Date) => {
  return time.getTime() > new Date().getTime() - 8.64e7 + 24 * 60 * 60 * 1000;
};
// 禁用时
const disabledHours = () => {
  const todayDate = new Date().setHours(0, 0, 0, 0);
  const selectDate = new Date(formValue.value.startTime.slice(0, 10)).setHours(0, 0, 0, 0);
  const arrs = [];
  if (selectDate >= todayDate) {
    for (let i = 0; i < 24; i++) {
      if (new Date().getHours() >= i) continue;
      arrs.push(i);
    }
  }
  return arrs;
};
// 禁用分
const disabledMinutes = () => {
  const todayDate = new Date().setHours(0, 0, 0, 0);
  const selectDate = new Date(formValue.value.startTime.slice(0, 10)).setHours(0, 0, 0, 0);
  const arrs = [];
  if (selectDate >= todayDate) {
    for (let i = 0; i < 60; i++) {
      if (new Date().getMinutes() >= i) continue;
      arrs.push(i);
    }
  }
  return arrs;
};
// 禁用秒
const disabledSeconds = () => {
  const todayDate = new Date().setHours(0, 0, 0, 0);
  const selectDate = new Date(formValue.value.startTime.slice(0, 10)).setHours(0, 0, 0, 0);
  const arrs = [];
  if (selectDate >= todayDate) {
    for (let i = 0; i < 60; i++) {
      if (new Date().getSeconds() >= i) continue;
      arrs.push(i);
    }
  }
  return arrs;
};
// 删除表格某一行
const handleDelete = (index: any) => {
  formValue.value.tableData.splice(index, 1);
};
// 批量设置number
const batchSetQuantityNumber = () => {
  selectIds.value.forEach(val => {
    formValue.value.tableData.forEach((v, i) => {
      if (val === v.id) {
        v.quantity = quantityNumber.value;
      }
    });
  });
};
// 库存地块下拉框
const querySelectList = async () => {
  //地块
  storeLocationList.value = await queryDictData({ typeCode: "HSE_MATERIAL_FAC" });
};
//批量设置供货商
const batchSetsupplierNumber = () => {
  selectIds.value.forEach(val => {
    formValue.value.tableData.forEach((v, i) => {
      if (val === v.id) {
        v.supplier = supplierNumber.value;
      }
    });
  });
};
// 批量设置生产日期
const batchSetproductionDateNumber = () => {
  selectIds.value.forEach(val => {
    formValue.value.tableData.forEach((v, i) => {
      if (val === v.id) {
        v.productionDate = productionDateNumber.value;
      }
    });
  });
};
// 批量设置到期日期
const batchSetexpirationDateNumber = () => {
  selectIds.value.forEach(val => {
    formValue.value.tableData.forEach((v, i) => {
      if (val === v.id) {
        v.expirationDate = expirationDateNumber.value;
      }
    });
  });
};
// 返回主页面
const backMainPage = () => {
  PxMessageBox.confirm("内容未保存，确认退出此出库单吗", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      formRef.value?.resetFields();
      emits("backMainPage");
    })
    .catch(() => {});
};
// 关闭子级dialog弹窗
const closeDialog = () => {
  dialogVisible.value = false;
};
// 选择物资后添加表格数据
const addTableRow = val => {
  const arr = [];
  val.forEach(item => {
    if (val && val.length > 0) {
      item.materialCode = item.code;
      arr.push(item);
    }
  });
  formValue.value.tableData = [...arr, ...formValue.value.tableData];
};
// // 导入
const addTableRowList = val => {
  if (val && val.length > 0) {
    const arr = [];
    formValue.value.tableData?.forEach(item => {
      arr.push(item.id);
    });
    const arr2 = [];
    val.forEach(item => {
      if (!arr.includes(item.id)) {
        item.materialCode = item.materialCode;
        arr2.push(item);
      }
    });
    formValue.value.tableData = [...arr2, ...formValue.value.tableData];
  }
};
// 判断入库量都有值，不为0或者"""
const judgeQuantity = () => {
  if (formValue.value.tableData.length > 0) {
    const arr = [];
    formValue.value.tableData.forEach(item => {
      arr.push(item.quantity);
    });
    return arr.every((value, index) => {
      return value != 0 && value != "";
    });
  } else {
    return false;
  }
};
// 判断入库物资列表不能为空
const judgeQuantity1 = () => {
  if (formValue.value.tableData.length > 0) {
    const arr = [];
    formValue.value.tableData.forEach(item => {
      arr.push(item.name);
    });
    return arr.every((value, index) => {
      return value != "-" && value != "";
    });
  } else {
    return false;
  }
};
// 判断入库库存地块不能为空
const judgeQuantity2 = () => {
  if (formValue.value.tableData.length > 0) {
    const arr = [];
    formValue.value.tableData.forEach(item => {
      arr.push(item.storeLocation);
    });
    return arr.every((value, index) => {
      return value != 0 && value != "" && value != null && value != undefined;
    });
  } else {
    return false;
  }
};
// 保存草稿
const handleInit = () => {
  if (formValue.value.tableData && formValue.value.tableData.length > 0) {
    const arr = [];
    if (formValue.value.inType === "PR/PO") {
      formValue.value.tableData.forEach(item => {
        arr.push({
          materialCode: item.materialCode,
          quantity: item.quantity,
          supplier: item.supplier,
          productionDate: item.productionDate,
          expirationDate: item.expirationDate,
          storeLocation: item.storeLocation
        });
      });
    } else if (formValue.value.inType === "MM领用") {
      formValue.value.tableData.forEach(item => {
        arr.push({
          materialCode: item.materialCode,
          quantity: item.quantity,
          supplier: item.supplier,
          productionDate: item.productionDate,
          expirationDate: item.expirationDate,
          storeLocation: item.storeLocation
        });
      });
    } else if (formValue.value.inType === "NPPA") {
      formValue.value.tableData.forEach(item => {
        arr.push({
          materialCode: item.materialCode,
          quantity: item.quantity,
          supplier: item.supplier,
          productionDate: item.productionDate,
          expirationDate: item.expirationDate,
          storeLocation: item.storeLocation
        });
      });
    } else if (formValue.value.inType === "Other") {
      formValue.value.tableData.forEach(item => {
        arr.push({
          materialCode: item.materialCode,
          quantity: item.quantity,
          supplier: item.supplier,
          productionDate: item.productionDate,
          expirationDate: item.expirationDate,
          storeLocation: item.storeLocation
        });
      });
    }
    formValue.value.inInventoryList = arr;
    formValue.value.approveStatus = "init";
    // facCode字段说明：facCode是要求必传的，用来却分一二期隔离用的
    const params = { ...formValue.value, purchaseNum: formValue.value.purchaseNum, facCode: formValue.value?.tableData[0]?.facCode || "" };
    PxMessageBox.confirm("确认保存草稿吗", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true
    })
      .then(async () => {
        if (props.drawerType === "add") {
          await materialInCreate(params);
          PxMessage.success("保存草稿成功");
          emits("backMainPage");
          emits("queryTable");
        } else if (props.drawerType === "edit") {
          await materialInEdit(params);
          PxMessage.success("编辑草稿成功");
          emits("backMainPage");
          emits("queryTable");
        }
      })
      .catch(() => {});
  } else {
    PxMessage.error("物资列表不能为空");
  }
};
// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      if (formValue.value.tableData && formValue.value.tableData.length > 0) {
        if (!judgeQuantity1()) {
          PxMessage.error("物资名称不能为空");
          return;
        }
        if (!judgeQuantity()) {
          PxMessage.error("入库数量不能为空");
          return;
        }
        if (!judgeQuantity2()) {
          PxMessage.error("存放地块不能为空");
          return;
        }
        const arr = [];
        if (formValue.value.inType === "PR/PO") {
          formValue.value.tableData.forEach(item => {
            arr.push({
              materialCode: item.materialCode,
              quantity: item.quantity,
              supplier: item.supplier,
              productionDate: item.productionDate,
              expirationDate: item.expirationDate,
              storeLocation: item.storeLocation
            });
          });
        } else if (formValue.value.inType === "MM领用") {
          formValue.value.tableData.forEach(item => {
            arr.push({
              materialCode: item.materialCode,
              quantity: item.quantity,
              supplier: item.supplier,
              productionDate: item.productionDate,
              expirationDate: item.expirationDate,
              storeLocation: item.storeLocation
            });
          });
        } else if (formValue.value.inType === "NPPA") {
          formValue.value.tableData.forEach(item => {
            arr.push({
              materialCode: item.materialCode,
              quantity: item.quantity,
              supplier: item.supplier,
              productionDate: item.productionDate,
              expirationDate: item.expirationDate,
              storeLocation: item.storeLocation
            });
          });
        } else if (formValue.value.inType === "Other") {
          formValue.value.tableData.forEach(item => {
            arr.push({
              materialCode: item.materialCode,
              quantity: item.quantity,
              supplier: item.supplier,
              productionDate: item.productionDate,
              expirationDate: item.expirationDate,
              storeLocation: item.storeLocation
            });
          });
        }
        formValue.value.inInventoryList = arr;
        formValue.value.approveStatus = "approving";
        // facCode字段说明：facCode是要求必传的，用来却分一二期隔离用的
        const params = { ...formValue.value, purchaseNum: formValue.value.purchaseNum, facCode: formValue.value.tableData[0].facCode };
        PxMessageBox.confirm("确认提交物资吗", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
          draggable: true
        })
          .then(async () => {
            if (props.drawerType === "add") {
              await materialInCreate(params);
              PxMessage.success("新增成功");
              emits("backMainPage");
              emits("queryTable");
            } else if (props.drawerType === "edit") {
              await materialInEdit(params);
              PxMessage.success("编辑成功");
              emits("backMainPage");
              emits("queryTable");
            }
          })
          .catch(() => {});
      } else {
        PxMessage.error("物资列表不能为空");
      }
    }
  });
};
</script>
<style lang="scss" scoped>
@import url("@/views/erc/scss/add-detail.scss");

:deep(.px-row) {
  width: 100%;
}

.img {
  display: flex;
  align-items: center;
  width: 100%;

  /* 垂直居中 */
  height: 22px;

  /* 大盒子的高度 */
  margin-bottom: 8px;
  font-size: 14px;
}

.imgBox {
  width: 3px;
  height: 16px;
  margin-right: 9px;
  background: #3b82f6;
  border-radius: 0 100px 100px 0;
}

.imgSize {
  height: 22px;
  font-size: 14px;
  font-weight: 600;
  line-height: 22px;
  color: rgb(0 0 0 / 80%);
}

.number {
  display: flex;
  margin-top: 20px;
}

:deep(.px-form-item__label) {
  width: 160px !important;
}
</style>
